<template>
  <ChartCard 
    :title="title" 
    :loading="loading" 
    :chart-data="chartData" 
    :chart-options="chartOptions"
    type="bar"
  />
</template>

<script setup>
import { ref, watch } from 'vue'
import ChartCard from './ChartCard.vue'

const props = defineProps({
  title: {
    type: String,
    default: '柱状图'
  },
  loading: {
    type: Boolean,
    default: false
  },
  data: {
    type: Array,
    default: () => []
  }
})

// 图表数据
const chartData = ref({
  labels: [],
  datasets: []
})

// 图表配置
const chartOptions = ref({
  plugins: {
    legend: {
      display: false
    }
  },
  scales: {
    y: {
      beginAtZero: true
    }
  },
  elements: {
    bar: {
      borderRadius: 4,
      borderSkipped: false
    }
  }
})

// 处理数据变化
watch(() => props.data, (newData) => {
  if (newData && newData.length > 0) {
    const colors = [
      'rgb(34, 197, 94)',   // green
      'rgb(239, 68, 68)',   // red
      'rgb(59, 130, 246)',  // blue
      'rgb(251, 191, 36)',  // yellow
      'rgb(168, 85, 247)',  // purple
      'rgb(236, 72, 153)'   // pink
    ]
    
    chartData.value = {
      labels: newData.map(item => item.label),
      datasets: [{
        label: '数据',
        data: newData.map(item => item.value),
        backgroundColor: newData.map((_, index) => colors[index % colors.length]),
        borderColor: newData.map((_, index) => colors[index % colors.length]),
        borderWidth: 0
      }]
    }
  }
}, { immediate: true })
</script>